package com.haizhi.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Objects;

public class Tools {

    private static Logger logger = LoggerFactory.getLogger(Tools.class);

    public static String getCurrentTime() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        return df.format(new Date());
    }

    //转换成base64编码
    public static String stringToBase64(String origin) {
        // 编码
        String asB64 = null;
        try {
            asB64 = Base64.getEncoder().encodeToString(origin.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("ERROR", e);
        }
        return asB64;
    }

    //从base64转换成字符串
    public static String base64ToString(String base64) {
        // 解码
        byte[] asBytes = Base64.getDecoder().decode(base64);

        try {
            return new String(asBytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("ERROR", e);
        }
        return null;
    }

    public static void createDirs(String filePath) {

        if (filePath == null || Objects.equals(filePath, "")) {
            logger.error("filepath 不合法..");
            return;
        }

        Path realPath = Paths.get(filePath);
        createDirs(realPath);
    }

    public static void createDirs(Path filePath) {

        if (filePath == null) {
            logger.error("filepath 不合法..");
            return;
        }

        if (!Files.exists(filePath.getParent())) {
            try {
                Files.createDirectories(filePath.getParent());
                logger.info("文件夹不存在, 创建文件夹: {}", filePath.getParent());
            } catch (IOException e) {
                logger.error("创建文件夹失败..");
                logger.error("ERROR:", e);
            }
        }
    }


}
